//
//  QZDetailVC.m
//  map
//
//  Created by 000 on 16/10/12.
//  Copyright © 2016年 faner. All rights reserved.
//

#import "QZDetailVC.h"
#import "BmobSDK/Bmob.h"
#import "QZAnnotation.h"
#import "QZAnnotationView.h"
#import "QZCancleVC.h"


@interface QZDetailVC ()<MKMapViewDelegate,CLLocationManagerDelegate,QZCancleVCDelegate>
{
    NSMutableArray *detailDeskmArray;
    NSMutableArray *partline;
    NSMutableArray *breakPmArray;
    NSMutableArray *linkParts;
    NSMutableArray *lineDeskArray;
    
    NSMutableArray *ApinLeftPicArray;
    
}
@property (nonatomic, strong) CLLocationManager *locationManager;//定位坐标
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@property (nonatomic, assign) CLLocationCoordinate2D firstCoordinate;
@property (nonatomic, strong) CLGeocoder *geocoder;//地理编码用
@property (nonatomic, strong) QZCancleVC *cancleVC;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
- (IBAction)backBC:(id)sender;
@end

@implementation QZDetailVC
- (CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate = self;
        //每隔多远定位一次
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        
        [_locationManager startUpdatingLocation];
        //精确度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _locationManager;
}

- (CLGeocoder *)geocoder
{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}
- (QZCancleVC *)cancleVC
{
    if (_cancleVC == nil) {
        _cancleVC = [[QZCancleVC alloc] init];
        _cancleVC.delegate = self;
    }
    return _cancleVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadBreakPCount];
    [self location];
    
}
- (void)location
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.026416, 0.019511);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.currentCoordinate, span);
    [self.mapView setRegion:region animated:YES];
    //显示用户的位置
    self.mapView.showsUserLocation = YES;
    //    self.mapView.mapType = MKMapTypeStandard;
    //追踪用户的位置
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadBreakPCount
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"breakPoints"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        breakPmArray = [NSMutableArray array];
        for (BmobObject *obj in array) {
            NSString *breakPoints = [obj objectForKey:@"breakPointCount"];
            [breakPmArray addObject:breakPoints];
        }
        [self loadDetailAnData];
    }];
    
}

- (void)loadDetailAnData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"annotations"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
//        DetarilAllObjectId = [NSMutableArray array];
        detailDeskmArray = [NSMutableArray array];
        partline = [NSMutableArray array];
        ApinLeftPicArray = [NSMutableArray array];
        NSString *leftPic;
        NSData *decodedImageData;
        for (BmobObject *obj in array) {
//            detailObId = [obj objectForKey:@"objectId"];
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.coordinate = CLLocationCoordinate2DMake([[obj objectForKey:@"latitude"] doubleValue], [[obj objectForKey:@"longitude"] doubleValue]);
            deskAn.title = [obj objectForKey:@"title"];
            leftPic = [obj objectForKey:@"imageStr"];
            decodedImageData = [[NSData alloc] initWithBase64Encoding:leftPic];
            UIImage *decodedImage      = [UIImage imageWithData:decodedImageData];
            deskAn.image = decodedImage;
            
            deskAn.subtitle = [obj objectForKey:@"subtitle"];
            
            
            CLLocation *pCl = [[CLLocation alloc] initWithLatitude:deskAn.coordinate.latitude longitude:deskAn.coordinate.longitude];
            [partline addObject:pCl];
            [ApinLeftPicArray addObject:leftPic];
            [detailDeskmArray addObject:deskAn];
        }
//        [self.mapView addAnnotations:detailDeskmArray];
        [self needLoadAns];
        
    }];
}

- (void)needLoadAns
{
    int start = 0;
    int end = 0;
    lineDeskArray = [NSMutableArray array];
    linkParts = [NSMutableArray array];
    for (int i = 0; i<breakPmArray.count; i++) {
        if (i< self.breakCount) {
            start = [breakPmArray[i] intValue]+start;
        }
        end = start + [breakPmArray[self.breakCount] intValue];
        
    }
    
    for (int i =0; i<detailDeskmArray.count; i++) {
        if (i>=start &&i<end) {
            [lineDeskArray addObject:detailDeskmArray[i]];
            [linkParts addObject:partline[i]];
        }
    }
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView addAnnotations:lineDeskArray];
    [self linkLines];

    /*--------------------____*/
   
}

- (void)linkLines
{
    int pointCount = (int)linkParts.count;
    CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i<pointCount; ++i) {
        CLLocation *location = [linkParts objectAtIndex:i];
        coordinateArray[i] = [location coordinate];
    }
    MKPolyline *grayLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapView addOverlay:grayLine];
        [self.mapView setVisibleMapRect:[grayLine boundingMapRect] animated:YES];
        
    });

}
- (IBAction)backBC:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.currentCoordinate = userLocation.coordinate;
}
#pragma mark 制作大头针
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //如果是当前位置就设置为nil
    if (annotation == mapView.userLocation) {
        return nil;
    }else{
        QZAnnotation *myAnnotation = [[QZAnnotation alloc] init];
        myAnnotation = annotation;
        QZAnnotationView *myAnnotationView = [QZAnnotationView getQZAnnotationViewWithMapView:mapView andAnnotation:annotation];
        
        myAnnotationView.image = [UIImage imageNamed:@"desk"];
        [myAnnotationView.leftButton setBackgroundImage:myAnnotation.image forState:UIControlStateNormal];
        return myAnnotationView;
    }
    
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.lineWidth   = 4.0;
    polylineView.strokeColor = [UIColor colorWithRed:245.0/255.0 green:130.0/255.0 blue:45.0/255.0 alpha:1.0];
    
    return polylineView;
}

- (void)cancleVC:(QZCancleVC *)cancleVC didSelectRowAtIndexPath:(int)indexPath
{
    self.breakCount = indexPath;
}

@end
